const express = require('express');

const static = require('express-static');

const cookieParser = require('cookie-parser');

const cookieSession = require('cookie-session');

const bodyParser = require('body-parser');

const consolidate = require('consolidate');

//导入数据库模块
const Db = require('./db.js');


const ejs = require('ejs');



// const jade = require('jade');

var server = express();

server.listen(8080);

var secret = '1234jdkfha';
//1.解析cookie
server.use(cookieParser(secret));
//2.使用session
var arr = [];
for(var i=0;i<10000;i++){
    arr.push('keys_'+Math.random());
}
server.use(cookieSession({
    name:'sessionid',
    keys:arr,
    maxAge:20*3600*1000
}))
//3.post数据
server.use(bodyParser.urlencoded({extended:false}))


server.set('view engine','html');

server.set('views','./views');

server.engine('html',consolidate.ejs);

// 首页
server.get('/',(req,res)=>{

    Promise.all([Db.query("SELECT * FROM `blog_banner`;"),Db.query("SELECT aid,title,avatar,content FROM `blog_article`;")]).then((data)=>{
        let sendData = {
            banners:data[0],
            articles:data[1]
        }
        res.render('index.ejs',sendData);
    }).catch((err)=>{
        res.status(500).send('数据库错误').end();
    })

})

//文章内容页
server.get('/article',(req,res)=>{
    let aid = req.query.aid;
    let sql = "SELECT * FROM `blog_article` WHERE aid="+aid;
    Db.query(sql).then((data)=>{
        res.render('article.ejs',{article:data[0]});
    }).catch((err)=>{
        res.status(500).send('数据库错误:'+err).end();
    })
})


//4.static数据
server.use(static('./www'));
